<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/8/9
 * Time: 17:29
 */
namespace app\wchat\controller;
use think\App;
use think\Request;
class Enginme extends Common
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }

    /**
     * 任务列表
     * @return mixed
     */
    public function listUI(){
        return $this->fetch('list');
    }

    /**
     * 工具列表
     * @return mixed
     */
    public function toolsUI(){

        return $this->fetch('tools');
    }

    /**
     * 工具添加
     * @return mixed
     */
    public function addToolsUI(){
        $tylist = db('tools_type')->order('sort asc')->select();
        return $this->fetch('addTools',['tylist'=>$tylist]);
    }

    /**
     * 任务详情页面
     * @return mixed
     */
    public function getUI(){
        return $this->fetch('get');
    }

    /**
     * 完成提交页面
     * @return mixed
     */
    public function complUI(){
        return $this->fetch('complete');
    }

    /**
     * 跟踪页面
     * @return mixed
     */
    public function trackUI(){
        return $this->fetch('enter/track');
    }

    /**
     * 团队页面
     */
    public function teamUI(){
        return $this->fetch('team');
    }

    /**
     * 团队添加
     * @return mixed
     */
    public function teamAddUI(){
        return $this->fetch('teamAdd');
    }

    /**
     * 跟踪列表
     * @param Request $request
     */
    public function track(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];

        $rows = db('dispatch_flow')->alias('df')
            ->order('df.id desc')
            ->where('df.dispatch_id',$did)
            ->join('admin a','a.admin_id=df.admin_id','left')
            ->field(['df.*','a.username'])
            ->select();
        return ['code'=>1,'data'=>$rows];
    }

    /**
     * 添加跟踪
     * @param Request $request
     * @return array
     */
    public function addTrack(Request $request){
        $out = $request->param();

        if(empty($out['step'])) return ['code'=>0,'data'=>'step参数错误'];
        if(empty($out['content'])) return ['code'=>0,'data'=>'content参数错误'];
        if(empty($out['did'])) return ['code'=>0,'data'=>'did参数错误'];

        $input['icon']        = '/public/static/wx/img/progress-list/t'.$out['step'].".png";
        $input['admin_id']    = session('muid');
        $input['c_time']      = date('Y-m-d H:i:s',time());
        $input['dispatch_id'] = $out['did'];
        $input['content']     = $out['content'];
        $input['step']        = $out['step'];

        $row = db('dispatch_flow')->insertGetId($input);
        if($row)
            return ['code'=>1,'msg'=>'添加成功'];
        return ['code'=>0,'msg'=>'添加失败'];
    }

    //查询最后一次跟踪
    public function find(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];

        $info = db('dispatch_flow')->where('dispatch_id',$did)->order('step','desc')->value('step');

        if($info)
            return ['code'=>1,'data'=>$info];
        return ['code'=>0,'data'=>$info];
    }

    /**
     * 工具列表
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tools(Request $request){
        $input = $request->param();
        $rows = db('tools')->where(['state_id'=>30,'admin_id'=>1])
            ->where(function ($query)use($input){
                if(!empty($input['cid']))
                    $query->where('type_id',$input['cid']);
            })
            ->paginate($input['limit'])->toArray();
        $data = [];
        foreach ($rows['data'] as $v){

            if($v['check_date'])
                $v['sur_waring'] = $v['waring']-ceil((((time()-strtotime($v['check_date']))/60)/60)/24);

            $data[] = $v;
        }

        return ['code'=>1,'data'=>$data,'count'=>$rows['total']];
    }

    /**
     * 已选工具列表
     * @param Request $request
     * @return array
     */
    public function toolsed(Request $request){
        $dis = $request->param('id');
        $row = db('dispatch_tools')->alias('dt')
            ->where('dt.dispatch_id',$dis)
            ->join('tools t','t.id=dt.tools_id','left')
            ->join('admin a','a.admin_id=dt.admin_id','left')
            ->field(['t.*','a.username','a.name','a.admin_id'])
            ->select();

        $me = ['data'=>[]];
        $other = [];
        $ida = [];
        foreach ($row as $v){
            if($v['admin_id']==session('muid')){
                $me['username'] = $v['username'];
                $me['name'] = $v['name'];
                $me['data'][] = $v;
            }else{
                $ida[] = $v['admin_id'];
            }
        }
        array_unique($ida);
        foreach($ida as $v){
            $tem = [];
            foreach ($row as $vr){
                if($v == $vr['admin_id']){
                    $tem['username'] = $vr['username'];
                    $tem['name'] = $vr['name'];
                    $tem['data'][] = $vr;
                }
            }
            $other[] = $tem;
        }

        return ['code'=>1,'msg'=>'','data'=>['me'=>$me,'other'=>$other]];
    }

    /**
     * 添加工具
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addTools(Request $request){
        $did = $request->param('id');
        $tids = $request->param('tids');
        if(empty($did)) return ['code'=>0,'msg'=>'任务ID参数错误'];
        if(empty($tids)) return ['code'=>0,'msg'=>'工具ID参数错误'];
        $tids = explode(',',$tids);
        $dt = db('dispatch_tools')->where(['dispatch_id'=>$did,'admin_id'=>session('muid')])->select();

        $tem = [];
        $det = [];
        foreach ($tids as $v){
            $t = true;
            foreach ($dt as $vd){
                if($v == $vd['tools_id']){
                    $t = false;
                    break;
                }
            }
            if($t){
                $det[] = [
                    'dispatch_id'=>$did,
                    'admin_id'=>session('muid'),
                    'tools_id'=>$v
                ];
            }
        }
        if(count($det)>0){
            $row = db('dispatch_tools')->insertAll($det);
            if($row){

                return ['code'=>1,'msg'=>'添加工具完成'];
            }
        }
        return ['code'=>0,'msg'=>'未添加任何工具或您已添加过该工具'];
    }

    /**
     * 移除工具
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function removeTools(Request $request){
        $did = $request->param('did');
        $tid = $request->param('tid');
        if(empty($did)) return ['code'=>0,'msg'=>'任务ID参数错误'];
        if(empty($tid)) return ['code'=>0,'msg'=>'工具ID参数错误'];
        $row = db('dispatch_tools')->where(['admin_id'=>session('muid'),'dispatch_id'=>$did,'tools_id'=>$tid])->delete();
        if($row)
            return ['code'=>1,'msg'=>'移除成功'];
        return ['code'=>0,'msg'=>'移除失败'];
    }

    /**
     * 派单任务列表
     * @param Request $request
     * @return array
     */
    public function queryDis(Request $request){
        $input = $request->param();

        //$input['ids'] = [0];

        /*$at = db('dispatch_at')->where('admin_id',session('muid'))->field('dispatch_id')->select();

        foreach ($at as $v){
            $input['ids'][] = $v['dispatch_id'];
        }*/

        $input['admin_id'] = session('muid');

        $rows = db('dispatch')->alias('w')->order('w.id desc')->where(function ($query)use($input){

            //$query->where('w.id','in',$input['ids']);

            if(!empty($input['fault_id'])){
                $query->where('w.fault_id',$input['fault_id']);
            }
            if(!empty($input['state_id'])){
                $sis = explode(',',$input['state_id']);
                $query->where('w.state_id','in',$sis);
            }
            if(!empty($input['tel'])){
                $query->where('w.tel',$input['tel']);
            }

            if(!empty($input['key'])){
                $query->where('w.title|ws.number|w.tel','LIKE','%'.$input['key'].'%');
            }

            if(!empty($input['admin_id'])){
                $query->where('w.admin_id',$input['admin_id']);
            }
        })
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->paginate($input['limit'])
            ->toArray();
        return ['code'=>1,'msg'=>'获取成功!','data'=>$rows['data'],'count'=>$rows['total'],'rel'=>1];
    }

    /**
     * 获取任务
     * @param Request $request
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDis(Request $request){
        $did = $request->param('id');
        if(empty($did)) return ['code'=>0,'msg'=>'参数错误'];
        $row = db('dispatch')->alias('w')->where('w.id',$did)
            ->join('state st','st.id=w.state_id','left')
            ->join('fault ft','ft.id=w.fault_id','left')
            ->join('works ws','ws.id=w.works_id','left')
            ->join('admin a','a.admin_id=w.admin_id','left')
            ->field(['w.*','st.state_name','ft.title as fault_name','ws.attach as w_attach','ws.check_code','a.username'])
            ->find();
        $at = db('dispatch_at')->where(['admin_id'=>session('muid'),'dispatch_id'=>$did])->find();
        $row['is_lead'] = $at['is_lead'];//是否是领队人
        $row['is_conf'] = $at['is_conf'];//是否同意接单
        $row['cause'] = $at['cause'];//拒单原因

        if($row['admin_id'] == session('muid')){
            return ['code'=>1,'msg'=>'','data'=>$row];
        }
        if($at){
            return ['code'=>1,'msg'=>'','data'=>$row];
        }
        return ['code'=>0,'msg'=>'您不是该任务的团队人员','data'=>[]];
    }

    /**
     * 确认接单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function conf(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'参数错误'];
        $row = db('dispatch_at')->where(['dispatch_id'=>$did,'admin_id'=>session('muid')])->update(['is_conf'=>1]);
        if($row){
            return ['code'=>1,'msg'=>'确认成功'];
        }
        return ['code'=>0,'msg'=>'确认失败'];
    }

    /**
     * 工程师接单-自己派单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function confMe(Request $request){

        $id = $request->param('dis_id');
        if(empty($id)) return ['code'=>0,'msg'=>'id参数错误'];
        $row = db('dispatch')->where('id',$id)->where('admin_id',session('muid'))->update(['state_id'=>25]);
        if($row){

            db('dispatch_at')->where(['dispatch_id'=>$id,'admin_id'=>session('muid')])->update(['is_conf'=>1]);
            $info = db('admin')->where('admin_id',session('muid'))->find();
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t1.png";
            $input['admin_id']    = session('muid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已接单";
            $input['step']        = 1;
            db('dispatch_flow')->insert($input);
            $input['icon']        = "/public/static/wx/img/progress-list/t2.png";
            $input['admin_id']    = session('muid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $id;
            $input['content']     = $info['name']."已组建团队";
            $input['step']        = 2;
            db('dispatch_flow')->insert($input);

            return ['code'=>1,'msg'=>'接单成功'];
        }
        return ['code'=>0,'msg'=>'接单失败'];
    }

    /**
     * 拒单
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function unconf(Request $request){
        $did = $request->param('dis_id');
        $val = $request->param('val');
        if(empty($did)) return ['code'=>0,'msg'=>'参数错误'];
        $row = db('dispatch_at')->where(['dispatch_id'=>$did,'admin_id'=>session('muid')])->update(['is_conf'=>-1,'cause'=>$val]);
        if($row)
            return ['code'=>1,'msg'=>'拒单成功'];
        return ['code'=>0,'msg'=>'拒单失败'];
    }

    /**
     * 完成工单，上传文件
     * @param Request $request
     */
    public function comp(Request $request){
        $did = $request->param('dis_id');
        $did = (int)$did;
        if(empty($did)) return json(['code'=>0,'msg'=>'参数错误，请返回重新提交']);
        $args = [];
        $files = request()->param('files');
        if(count($files)>0)
            foreach($files as $file){
                $info = base64_image_content($file,APP_PATH .'/uploads/arga/'.$did);
                if($info){
                    $args[] = '/uploads/arga/'.$did.'/'.$info;
                }else{
                    return json(['code'=>0,'msg'=>'文件上传失败']);
                }
            }
        else
            return json(['code'=>0,'msg'=>'没有提交文件信息']);

        $ns = '';
        foreach ($args as $v){
            $ns .= $v.';';
        }
        $input = [
            'id'=>$did,
            'state_id'=>24,
            'arge'=>$ns
        ];

        $row = db('dispatch')->where('id',$input['id'])->update($input);

        if($row){
            $input = [];
            $input['icon']        = "/public/static/wx/img/progress-list/t9.png";
            $input['admin_id']    = session('muid');
            $input['c_time']      = date('Y-m-d H:i:s',time());
            $input['dispatch_id'] = $did;
            $input['content']     = "已上传完成协议";
            $input['step']        = 9;
            db('dispatch_flow')->insert($input);

            $team = db('dispatch_at')->where('dispatch_id',$did)->select();
            $ids_arr = [];
            foreach ($team as $v){
                $ids_arr[] = $v['admin_id'];
            }

            db('admin')->where('admin_id','in',$ids_arr)->update(['is_at'=>0]);


            return json(['code'=>1,'msg'=>'信息提交成功']);
        }

        return json(['code'=>0,'msg'=>'信息提交失败']);
    }

    /**
     * 工具票上传
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function ticket(Request $request){
        $did = $request->param('dis_id');
        $did = (int)$did;
        if(empty($did)) return json(['code'=>0,'msg'=>'参数错误，请返回重新提交']);
        $args = [];
        $args_gu = [];
        $files = request()->param('files');

        $gufile = request()->param('gu');

        if(count($files)<=0 && count($gufile)<=0)
            return json(['code'=>0,'msg'=>'没有提交文件信息']);
        if(count($files)>0)
            foreach($files as $file){
                $info = base64_image_content($file,APP_PATH .'/uploads/arga/'.$did);
                if($info){
                    $args[] = '/uploads/arga/'.$did.'/'.$info;
                }else{
                    return json(['code'=>0,'msg'=>'文件上传失败']);
                }
            }
        if(count($gufile)>0)
            foreach($gufile as $file){
                $info = base64_image_content($file,ROOT_PATH .'uploads/arga/'.$did);
                if($info){
                    $args_gu[] = '/uploads/arga/'.$did.'/'.$info;
                }else{
                    return json(['code'=>0,'msg'=>'文件上传失败']);
                }
            }

        $ns = '';
        foreach ($args as $v){
            $ns .= $v.';';
        }
        if($ns != '') $ns = substr($ns,0,-1);
        $gu = '';
        foreach ($args_gu as $v){
            $gu .= $v.';';
        }
        if($gu != '') $gu = substr($gu,0,-1);
        $input = [
            'id'=>$did,
            'ticket'=>$ns,
            'guard'=>$gu
        ];
        $row = db('dispatch')->where('id',$input['id'])->update($input);

        if($row)
            return json(['code'=>1,'msg'=>'上传成功']);
        return json(['code'=>0,'msg'=>'上传失败']);
    }

    /**
     * 工程师列表
     * @param Request $request
     * @return array
     */
    public function query(Request $request){
        $input = $request->param();
        $input['gid'] = 5;
        $input['is_part'] = 0;
        $rows = db('admin')->alias('a')->where(function ($query)use($input){
            if(!empty($input['gid']))
                $query->where('a.group_id',$input['gid']);
            /*if(isset($input['is_part']))
                $query->where('a.is_part',$input['is_part']);*/
            if(!empty($input['aid']))
                $query->where('a.admin_id',$input['aid']);
            /*if(!empty($input['apid']))
                $query->where('a.a_pid',$input['apid']);*/
            if(isset($input['is_at']))
                $query->where('a.is_at',$input['is_at']);
        })
            ->join('auth_group ag','a.group_id=ag.group_id','left')
            ->join('jobs js','js.id=a.jobs_id','left')
            ->field(['a.*,ag.title','js.title as jobs_title'])
            ->select();
        return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$rows,'rel'=>1];
    }
    /**
     * 添加团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addTeam(Request $request){
        $did = $request->param('dis_id');
        $aids = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aids)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::addTeam($did,$aids);
    }

    /**
     * 移除团队人员
     * @param Request $request
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove(Request $request){
        $did = $request->param('dis_id');
        $aid = $request->param('aid');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        if(empty($aid)) return ['code'=>0,'msg'=>'aid参数错误'];
        return \app\repository\Dispatch::remove($did,$aid);
    }


    /**
     * 任务团队
     * @param Request $request
     * @return array
     */
    public function teamList(Request $request){
        $did = $request->param('dis_id');
        if(empty($did)) return ['code'=>0,'msg'=>'dis_id参数错误'];
        $rows = db('dispatch_at')->alias('da')
            ->where('da.dispatch_id',$did)
            ->join('admin a','a.admin_id=da.admin_id','left')
            ->join('jobs j','j.id=a.jobs_id','left')
            ->field(['a.*','j.title as jobs_title','da.is_lead'])
            ->select();
        return ['code'=>1,'data'=>$rows];
    }
}